package com.hanthink.system.service.impl.resourcecall;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.util.StringUtil;
import com.hanthink.common.constant.BusinessConstants;
import com.hanthink.common.constant.Constants;
import com.hanthink.common.exception.CustomException;
import com.hanthink.common.utils.DateUtils;
import com.hanthink.common.utils.SerialNumberUtil;
import com.hanthink.common.utils.StringUtils;
import com.hanthink.system.domain.SysSerialNumber;
import com.hanthink.system.domain.message.NewsRecordInfo;
import com.hanthink.system.domain.pc.EmEquip;
import com.hanthink.system.domain.repair.EquipRepairMessageVo;
import com.hanthink.system.domain.resourcecall.CallRecordFile;
import com.hanthink.system.domain.resourcecall.CallRecordInfo;
import com.hanthink.system.domain.resourcecall.ResourceCallInfo;
import com.hanthink.system.mapper.EmEquipMapper;
import com.hanthink.system.mapper.SysSerialNumberMapper;
import com.hanthink.system.mapper.repair.EquipRepairMapper;
import com.hanthink.system.mapper.resourcecall.ResourceCalFilelMapper;
import com.hanthink.system.mapper.resourcecall.ResourceCallMapper;
import com.hanthink.system.service.resourcecall.IResourceCallInfoService;

@Service
public class ResourceCallInfoServiceImpl implements IResourceCallInfoService {

	@Autowired
	private ResourceCallMapper resourceCallMapper;
	@Autowired
	private SysSerialNumberMapper sysSerialNumberMapper;

	@Autowired
	private EmEquipMapper emEquipMapper;

	@Autowired
	private ResourceCalFilelMapper resourceCalFilelMapper;

	@Autowired
	private EquipRepairMapper equipRepairMapper;

	@Override
	public ResourceCallInfo selectEquipDescByEquipName(ResourceCallInfo info) {
		// 判断设备编码是否为空
		String equipName = info.getEquipName();
		if (equipName == null || "".equals(equipName)) {
			throw new CustomException("设备编码为空");
		}
		List<ResourceCallInfo> list = resourceCallMapper.selectEquipDescByEquipName(info);
		if (list == null || list.size() < 1) {
			throw new CustomException("未查询到设备名称");
		}
		return list.get(0);
	}

	@Override
	public List<ResourceCallInfo> selectListOfResourceCall(ResourceCallInfo info) {
		// 获取ID
		if ("1".equals(info.getType())) {
			info.setTypeCode(BusinessConstants.RESOURCE_CALL_PRODUCTION);
		} else if ("2".equals(info.getType())) {
			info.setTypeCode(BusinessConstants.RESOURCE_CALL_LOGISTICS);
		} else if ("3".equals(info.getType())) {
			info.setTypeCode(BusinessConstants.RESOURCE_CALL_QUILITY);
		} else {
			throw new CustomException("未查询到界面类型，请联系管理员");
		}
		return resourceCallMapper.selectListOfResourceCall(info);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean save(CallRecordInfo info) {
		try {
			// 保存主表
			String newsType = "";
			if ("1".equals(info.getType())) {
				info.setTypeKey(BusinessConstants.RESOURCE_CALL_PRODUCTION);
				newsType = BusinessConstants.CALL_PRODUCTION_NAME;
			} else if ("2".equals(info.getType())) {
				info.setTypeKey(BusinessConstants.RESOURCE_CALL_LOGISTICS);
				newsType = BusinessConstants.CALL_LOGISTICS_NAME;
			} else if ("3".equals(info.getType())) {
				info.setTypeKey(BusinessConstants.RESOURCE_CALL_QUILITY);
				newsType = BusinessConstants.CALL_QUILITY_NAME;
			} else {
				throw new CustomException("未查询到界面类型，请联系管理员");
			}
			SysSerialNumber serial = sysSerialNumberMapper.selectNextValue();
			String callCode = SerialNumberUtil.getSerialNumber(BusinessConstants.CALL_FLAG, serial.getNextValue(),
					serial.getToday());
			info.setCallCode(callCode);
			info.setStatus(BusinessConstants.CALL_STATUS_NO_RES);
			resourceCallMapper.insertCallRecord(info);

			ResourceCallInfo resourcecallInfo = new ResourceCallInfo();
			resourcecallInfo.setCallCode(callCode);
			List<ResourceCallInfo> callInfos = resourceCallMapper.selectlistOfCallInfo(resourcecallInfo);

			if (callInfos.size() > 0) {
				// 保存报修文件信息
				CallRecordFile callRecordFile = null;
				if (ArrayUtils.isNotEmpty(info.getPicList())) {
					callRecordFile = new CallRecordFile();
					String picUrl = "";
					for (String pic : info.getPicList()) {
						picUrl += (pic + ";");
					}
					callRecordFile.setCallId(callInfos.get(0).getId());
					callRecordFile.setFilePath(picUrl);
					callRecordFile.setFileType(Constants.RESOURCE_PIC);
					resourceCalFilelMapper.insertCallRecordFile(callRecordFile);
				}

				if (ArrayUtils.isNotEmpty(info.getVideoList())) {
					callRecordFile = new CallRecordFile();
					String videoUrl = "";
					for (String video : info.getVideoList()) {
						videoUrl += (video + ";");
					}
					callRecordFile.setCallId(callInfos.get(0).getId());
					callRecordFile.setFilePath(videoUrl);
					callRecordFile.setFileType(Constants.RESOURCE_VIDEO);
					resourceCalFilelMapper.insertCallRecordFile(callRecordFile);
				}

				if (ArrayUtils.isNotEmpty(info.getAudioList())) {
					callRecordFile = new CallRecordFile();
					String audioUrl = "";
					for (String audio : info.getAudioList()) {
						audioUrl += (audio + ";");
					}
					callRecordFile.setCallId(callInfos.get(0).getId());
					callRecordFile.setFilePath(audioUrl);
					callRecordFile.setFileType(Constants.RESOURCE_AUDIO);
					resourceCalFilelMapper.insertCallRecordFile(callRecordFile);
				}
			}

			// 判断问题等级
			ResourceCallInfo resourceCallInfo = new ResourceCallInfo();
			String faultRankRole = "0";
			if ("1".equals(info.getFaultRank())) {
				faultRankRole = "fault_important_role";
			} else if ("2".equals(info.getFaultRank())) {
				faultRankRole = "fault_urgent_role";
			}
			resourceCallInfo.setRole(faultRankRole);
			resourceCallInfo.setSiteKey(info.getSiteKey());
			// 查询问题等级关联通知用户
			List<ResourceCallInfo> callUsers = resourceCallMapper.UrgentCall(resourceCallInfo);
			if (callUsers.size() > 0) {
				for (ResourceCallInfo callInfo : callUsers) {
					if (StringUtils.isNull(callInfo)) {
						continue;
					}
					NewsRecordInfo news = new NewsRecordInfo();
					news.setEqKey(info.getEqKey());
					serial = sysSerialNumberMapper.selectNextValue();
					String newsCode = SerialNumberUtil.getSerialNumber(BusinessConstants.MESSAGE_FLAG,
							serial.getNextValue(), serial.getToday());
					news.setNewsCode(newsCode);
					switch (faultRankRole) {
					case "0":
						news.setNewsDesc("【一般呼叫:" + info.getCallReason() + "】\n请及时处理");
						break;
					case "1":
						news.setNewsDesc("【重要呼叫:" + info.getCallReason() + "】\n请及时处理");
						break;
					case "2":
						news.setNewsDesc("【紧急呼叫:" + info.getCallReason() + "】\n请及时处理");
						break;
					default:
						news.setNewsDesc("【问题呼叫:" + info.getCallReason() + "】\n请及时处理");
						break;
					}
					news.setNewsType(newsType);
					news.setNotingUser(callInfo.getUserName());
					news.setSendUser(info.getCallUser());
					news.setSiteKey(info.getSiteKey());
					news.setRelationId(callInfos.get(0).getId());
					resourceCallMapper.insertNewsRecord(news);
				}
			}

			// 保存子表
			List<ResourceCallInfo> nameList = resourceCallMapper.selectUserNameList(info);
			List<String> notingUserList = new ArrayList<String>();
			if (nameList != null && nameList.size() > 0) {
				for (int i = 0; i < nameList.size(); i++) {
					if (StringUtils.isNull(nameList.get(i)))
						continue;
					String tempName = nameList.get(i).getUserName();
					if (tempName != null && !"".equals(tempName) && !notingUserList.contains(tempName)) {
						notingUserList.add(tempName);
					}
				}
			}
			if (notingUserList.size() > 0) {
				// 根据设备id查询设备信息
				EmEquip emEquip = emEquipMapper.selectEmEquipById(info.getEqKey());
				for (int i = 0; i < notingUserList.size(); i++) {
					NewsRecordInfo news = new NewsRecordInfo();
					news.setEqKey(info.getEqKey());
					serial = sysSerialNumberMapper.selectNextValue();
					String newsCode = SerialNumberUtil.getSerialNumber(BusinessConstants.MESSAGE_FLAG,
							serial.getNextValue(), serial.getToday());
					news.setNewsCode(newsCode);
					news.setNewsDesc("【" + info.getCallReason() + "】\n" + emEquip.getDesc() + "[" + emEquip.getName()
							+ "]\n请及时响应");
					news.setNewsType(newsType);
					news.setNotingUser(notingUserList.get(i));
					news.setSendUser(info.getCallUser());
					news.setSiteKey(info.getSiteKey());
					news.setRelationId(callInfos.get(0).getId());
					resourceCallMapper.insertNewsRecord(news);
				}

				// 插入群通知
				EquipRepairMessageVo equipRepairMessageVo = new EquipRepairMessageVo();
				equipRepairMessageVo.setIsPush(BusinessConstants.IS_PUSH_TRUE);
				equipRepairMessageVo.setIsRead(BusinessConstants.IS_READ_FALSE);
				equipRepairMessageVo.setNewsType(newsType);
				equipRepairMessageVo.setSendUser(info.getCallUser());
				equipRepairMessageVo.setSiteKey(info.getSiteKey());
				equipRepairMessageVo.setEqKey(info.getEqKey());
				equipRepairMessageVo.setRelationId(callInfos.get(0).getId());
				equipRepairMessageVo.setNotingUser("@all");
				if (!StringUtil.isEmpty(callInfos.get(0).getRemark())) {
					equipRepairMessageVo.setNewsDesc("【资源呼叫】\n" + emEquip.getDesc() + "[" + emEquip.getName()
							+ "]\n呼叫时间：" + DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD_HH_MM_SS) + "\n呼叫描述:"
							+ callInfos.get(0).getRemark() + "\n 请及时响应");
				} else {
					equipRepairMessageVo.setNewsDesc("【资源呼叫】\n" + emEquip.getDesc() + "[" + emEquip.getName()
							+ "]\n呼叫时间：" + DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD_HH_MM_SS) + "\n 请及时响应");
				}

				// 保存呼叫推送信息
				equipRepairMapper.saveEquipRepairMessageInfo(equipRepairMessageVo);
			}
		} catch (Exception e) {

			throw new CustomException(e.getMessage());
		}

		return true;
	}

}
